package com.lagou.controller;

import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class FileController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile fileName) {

        String fileId = "";
        try {
            String originalFilename = fileName.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String newFileName = UUID.randomUUID().toString() + "." + suffix;
            File toSaveFile = new File("D:/upload/" + newFileName);
            fileName.transferTo(toSaveFile);
            String newFilePath = toSaveFile.getAbsolutePath();

            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;
            StorageClient1 client1 = new StorageClient1(trackerServer, storageServer);
            NameValuePair[] list = new NameValuePair[1];
            list[0] = new NameValuePair("fileName", originalFilename);
            fileId = client1.upload_file1(newFilePath, suffix, list);
            trackerServer.close();
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }

        return fileId;
    }
}
